package com.atguigu.helper;

import com.atguigu.entity.Permission;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: 翟文海
 * @Date: 2022/11/4/004 20:03
 * @Version: 1.0
 * @Description:
 **/
public class PermissionHelper {
    public static List<Permission> build(List<Permission> permissionList) {

        List<Permission> menu = permissionList.stream()
                .filter(permission -> permission.getParentId() == 0) //过滤出一级菜单: parentId是0
                .map(permission -> {
                    //给一级菜单设置子菜单
                    //1.查询出一级菜单的子菜单
                    permission.setChildren(getChildren(permission, permissionList));
                    //2. 设置菜单的级别
                    permission.setLevel(1);
                    return permission;
                })
                .collect(Collectors.toList());
        return menu;
    }

    public static List<Permission> getChildren(Permission permission, List<Permission> permissionList) {
        return permissionList.stream()
                .filter(p -> p.getParentId().equals(permission.getId()))
                .map(p -> {
                            p.setChildren(getChildren(p, permissionList));
                            return p;
                        }
                )
                .collect(Collectors.toList());
    }
}
